package com.flycms.common.utils;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 时间工具类
 * 
 * @author kaifei sun
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    private static final Logger logger = LoggerFactory.getLogger(Threads.class);

    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    private static final long m = 60*1000L;//分

    private static final long hour = 3600*1000L;//小时

    private static final long day = 24*hour;//天

    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }
    
    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 将字符串日期转换为字符串 , 格式yyyy-MM-dd HH:mm:ss
     *
     * @param date
     *            要转换的日期
     *
     * @return
     */
    public static String fomatDateToString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        return sdf.format(date);
    }

    /**
     * 将字符串日期转换为字符串 , 格式yyyy-MM-dd HH:mm:ss
     *
     * @param date
     *            要转换的日期
     *
     * @return
     */
    public static String fomatString(String date) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date d = fmt.parse(date);
            return fmt.format(d.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 校验日期是否合法
     *
     * @return
     */
    public static boolean isValidDate(String s) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            fmt.parse(s);
            return true;
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return false;
        }
    }

    /**
     * 校验日期是否合法,格式yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static boolean isValidDayDate(String s) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            fmt.parse(s);
            return true;
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return false;
        }
    }

    public static int getDiffYear(String startTime,String endTime) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            int years=(int) (((fmt.parse(endTime).getTime()-fmt.parse(startTime).getTime())/ (1000 * 60 * 60 * 24))/365);
            return years;
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return 0;
        }
    }
    /**
     * <li>功能描述：时间相减得到天数
     * @param beginDateStr
     * @param endDateStr
     * @return
     * long
     * @author Administrator
     */
    public static long getDaySub(String beginDateStr,String endDateStr){
        long day=0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate = null;
        Date endDate = null;

        try {
            beginDate = format.parse(beginDateStr);
            endDate= format.parse(endDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
        //System.out.println("相隔的天数="+day);

        return day;
    }

    /**
     * 得到n天之后的日期
     * @param days
     * @return
     */
    public static String getAfterDayDate(String days) {
        int daysInt = Integer.parseInt(days);

        Calendar canlendar = Calendar.getInstance(); // java.util包
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();

        SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdfd.format(date);

        return dateStr;
    }

    /**
     * 得到n天之后是周几
     * @param days
     * @return
     */
    public static String getAfterDayWeek(String days) {
        int daysInt = Integer.parseInt(days);

        Calendar canlendar = Calendar.getInstance(); // java.util包
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("E");
        String dateStr = sdf.format(date);

        return dateStr;
    }

    /**
     * 日期时间转换成文字
     * @param time
     * @return
     * @throws ParseException
     */
    public static String getDateTimeString(String time) throws ParseException{
        if(time==null){
            throw new NullPointerException();
        }
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date =sdf.parse(time);

        Date currentDate = new Date();
        long cha = Math.abs(date.getTime()-currentDate.getTime());
        long hours = cha/hour;
        if(hours<1){
            if(cha/m<=0){
                return "刚刚";
            }
            return cha/m+"分钟前";
        }
        if(hours<24){
            return cha/hour+"小时前";
        }
        if(hours<=720){
            int nn = Integer.valueOf(cha/day+"");
            if(cha%day>0){
                nn++;
            }
            return nn+"天前";
        }
        if(hours>720){
            int nn = Integer.valueOf(cha/day/30+"");
            if(cha%day%30>0){
                nn++;
            }
            return nn+"个月前";
        }
        return sdf.format(date);
    }

    /**
     * 站内短信显示日期时间转换成文字
     * @param time
     * @return
     * @throws ParseException
     */
    public static String getMessageDateTime(String time) throws ParseException{
        if(time==null){
            throw new NullPointerException();
        }
        Date newTime=new Date();
        //将下面的 理解成  yyyy-MM-dd 00：00：00 更好理解点
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //格式化成时间：分：秒
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");

        String todayStr = format.format(newTime);
        Date today = format.parse(todayStr);
        Date oldTime = sdf.parse(time);

        String dateString = formatter.format(oldTime);
        //昨天 86400000=24*60*60*1000 一天
        if((today.getTime()-oldTime.getTime())>0 && (today.getTime()-oldTime.getTime())<=86400000) {
            return "昨天 "+dateString;
        }
        else if((today.getTime()-oldTime.getTime())<=0){ //至少是今天
            return "今天 "+dateString;
        }
        return sdf.format(oldTime);
    }


    // 加天数
    public static String addDays(int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, day);
        StringBuffer sb = new StringBuffer();
        sb.append(calendar.get(Calendar.YEAR)).append("-");
        sb.append(calendar.get(Calendar.MONTH) + 1).append("-");
        sb.append(calendar.get(Calendar.DAY_OF_MONTH));
        return sb.toString();
    }

    // 加年份
    public static String addYears(String now, int year) throws ParseException {
        Calendar fromCal = Calendar.getInstance();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dateFormat.parse(now);
        fromCal.setTime(date);
        fromCal.add(Calendar.YEAR, year);

        return dateFormat.format(fromCal.getTime());
    }

    // 加天数(特定时间)
    public static String addDate(String now, int day) throws ParseException {
        Calendar fromCal = Calendar.getInstance();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dateFormat.parse(now);
        fromCal.setTime(date);
        fromCal.add(Calendar.DATE, day);

        return dateFormat.format(fromCal.getTime());
    }

    /**
     * 将日期转换为字符串 , 格式yyyy-MM-dd
     * @param birthDay 出生日期
     * @return
     * @throws Exception
     */
    public static String getAge(String birthDay) throws Exception {
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        Date date =sdf.parse(birthDay);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        Calendar now = Calendar.getInstance();
        int day = now.get(Calendar.DAY_OF_MONTH) - calendar.get(Calendar.DAY_OF_MONTH);
        int month = now.get(Calendar.MONTH) - calendar.get(Calendar.MONTH);
        int year = now.get(Calendar.YEAR) - calendar.get(Calendar.YEAR);
        //按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
        if(day<0){
            month -= 1;
            now.add(Calendar.MONTH, -1);//得到上一个月，用来得到上个月的天数。
            day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        if(month<0){
            month = (month+12)%12;
            year--;
        }
        String age="";
        if(year==0 && month==0){
            age += day+"天";
        }else if(year==0){
            age += month+"月"+day+"天";
        }else if(year>0 && day==0){
            age += year +"岁"+ month +"月";
        }else if(year>0 && day>0){
            age += year+"岁"+month+"月"+day+"天";
        }

        return age;
    }

    public static String fomatCurrentDate(String dateFomat) {
        String date=null;
        if("dd".equals(dateFomat)){
            SimpleDateFormat sDateFormat =new SimpleDateFormat("dd");
            date = sDateFormat.format(new Date());
        }else if("mm".equals(dateFomat)){
            SimpleDateFormat sDateFormat =new SimpleDateFormat("MM");
            date = sDateFormat.format(new Date());
        }else if("yyyy".equals(dateFomat)){
            SimpleDateFormat sDateFormat =new SimpleDateFormat("yyyy");
            date = sDateFormat.format(new Date());
        }else if("yyyymm".equals(dateFomat)){
            SimpleDateFormat sDateFormat =new SimpleDateFormat("yyyy-MM");
            date = sDateFormat.format(new Date());
        }else if("mmdd".equals(dateFomat)){
            SimpleDateFormat sDateFormat =new SimpleDateFormat("MM.dd");
            date = sDateFormat.format(new Date());
        }else if("week".equals(dateFomat)){
            Date time=new Date();
            String[] weeks = {"周日","周一","周二","周三","周四","周五","周六"};
            Calendar cal = Calendar.getInstance();
            cal.setTime(time);
            int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if(week_index<0){
                week_index = 0;
            }
            date = weeks[week_index];
        }
        return date;
    }


    public static Boolean isTimeStampValid(String timeStamp) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
        try{
            format.format(new Date(Long.valueOf(timeStamp)));;
            return true;
        }
        catch(Exception e)
        {
            return false;
        }
    }

    /**
     * String timeZoneConvert = timeZoneConvert(
     *              new Date().getTime()
     *              , "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
     *              "Asia/Shanghai");
     *
     * @param date 毫秒
     * @param pattern format时间格式
     * @param timeZone 时区
     * @return 如:2019-12-30T16:32:07.616+0800
     */
    public static String timeZoneConvert(Long date,String pattern,String timeZone){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat(pattern);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
        return simpleDateFormat.format(date);
    }

    /**
     * 将 yyyy-MM-dd'T'HH:mm:ss.SSS Z 转换成 Date
     */
    public static Date formateDate(String dateStr){
        try {
            dateStr = dateStr.replace("Z", " UTC");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
            return format.parse(dateStr);
        } catch (ParseException e) {
            logger.error("转换时间失败！", e);
        }
        return null;
    }

    /**
     *  处理时间格式 2019-11-28T06:52:09.724+0000 为 yyyy-MM-dd HH:mm:ss
     * */
    public static Date dealDateFormat(String oldDate) {
        Date date1 = null;
        DateFormat df2 = null;
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            Date date = df.parse(oldDate);
            SimpleDateFormat df1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
            return df1.parse(date.toString());
            //df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) throws IOException {

        System.out.println(dealDateFormat("2021-02-25T10:56:21.000+0800"));
    }
}
